package org.dochandler.faces.bean;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.dochandler.config.DHConfig;
import org.dochandler.faces.servicefactory.LoginServiceFacesFactory;
import org.dochandler.faces.util.FacesBean;
import org.dochandler.faces.util.FacesNav;
import org.dochandler.service.LoginService;
import org.dochandler.service.domain.Officer;
import org.dochandler.service.domain.Rank;
import org.dochandler.service.exception.AuthenticationException;

@SuppressWarnings("serial")
@ManagedBean
@SessionScoped
public class OfficerBean implements Serializable {
	private Long id;
	private String password;
	private String name;
	private LoginService loginService;
	
	
	public OfficerBean() {
		setLoginService( LoginServiceFacesFactory.getInstance().create() );
	}
	
	/**
	 * Performs the authentication
	 * @return
	 */
	public String login() {
		String pageKey;
		
		Officer officer;
		try {
			
			officer = getLoginService().login(id, password);
			
			if (officer.getRank().ordinal() >= Rank.CAPTAIN.ordinal() ) {
				pageKey = FacesNav.MISSION_FUNCIONS_LIST.pageKey();
			} else {
				pageKey = FacesNav.FUNCTIONS_LIST.pageKey();
			}
			
			getFacesCtx().getExternalContext().getSessionMap().put(FacesBean.OFFICER.beanKey(), officer);
			
		} catch(AuthenticationException e) {
			String message = DHConfig.getString("msg_login_invalid");
			getFacesCtx().addMessage("login_form", new FacesMessage(message));
			pageKey = FacesNav.LOGIN.pageKey();
		}
		return pageKey;
	}
	
	private FacesContext getFacesCtx() {
		return FacesContext.getCurrentInstance();
	}
	
	/*
	 * SETTERS AND GETTERS
	 */
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
	
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}